<script setup lang="ts">
import { useRouter } from 'vue-router';
import type { FieldType } from 'vant';
import type { PostData } from '@/types/login.ts';
import { registerPost, uploadPost } from '@/services/login.ts';
import { Md5 } from 'ts-md5';

const $router = useRouter();
const formRef = ref();
const loading = ref(false);
const passwordShow = ref<FieldType>('password');
const postData: PostData = reactive({
  customerName: '',
  organizingInstitutionCode: '',
  businessLicense: [],
  businessCardStartDate: '',
  businessCardEndDate: '',
  medicalInstitution: [],
  institutionCardStartDate: '',
  institutionCardEndDate: '',
  legalPersonName: '',
  legalPersonIdNumber: '',
  legalPersonCardPictureObverse: [],
  legalPersonCardPictureReverse: [],
  legalPersonCardStartDate: '',
  legalPersonCardEndDate: '',
  contactMan: '',
  contactPhone: '',
  registeredAddress: '',
  taxpayerId: '',
  depositBank: '',
  bankAccount: '',
  account: '',
  password: '',
  againPassword: '',
  checked: false,
});

const rules: any = reactive({
  customerName: [{ required: true, message: '请输入企业名称' }],
  organizingInstitutionCode: [{ required: false, message: '请输入组织机构代码' }],
  businessLicense: [{ required: true, message: '请上传营业执照' }],
  businessCardStartDate: [{ required: true, message: '请选择证件生效日期' }],
  businessCardEndDate: [{ required: true, message: '请选择证件失效日期' }],
  medicalInstitution: [{ required: true, message: '请上传医疗机构执业许可' }],
  institutionCardStartDate: [{ required: true, message: '请输入证件生效日期' }],
  institutionCardEndDate: [{ required: true, message: '请选择证件失效日期' }],
  legalPersonName: [{ required: false, message: '请输入法人姓名' }],
  legalPersonIdNumber: [{ required: false, message: '请输入法人身份证号' }],
  legalPersonCardStartDate: [{ required: false, message: '请选择证件生效日期' }],
  legalPersonCardEndDate: [{ required: false, message: '请输入证件失效日期' }],
  legalPersonCardPictureObverse: [{ required: false, message: '请上传身份证正面' }],
  legalPersonCardPictureReverse: [{ required: false, message: '请上传身份证反面' }],
  contactMan: [{ required: true, message: '请输入联系人' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
  registeredAddress: [{ required: true, message: '请输入注册地址' }],
  taxpayerId: [{ required: true, message: '请输入纳税人识别号' }],
  depositBank: [{ required: true, message: '请输入开户行' }],
  bankAccount: [{ required: true, message: '请输入银行账户' }],
  account: [
    { required: true, message: '请输入登录手机号' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
    },
  ],
  password: [
    { required: true, message: '密码不能为空' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$/,
      message: '长度应为8-15个字符，必须包含大写、小写字母和数字',
    },
  ],
  againPassword: [
    { required: true, message: '确认密码不能为空' },
    {
      validator: () => postData.password === postData.againPassword,
      message: '两次输入的密码不一致',
      trigger: 'blur',
    },
  ],
});

const onRegisterClick = async () => {
  try {
    await formRef.value.validate();
    if (!postData.checked) {
      showToast('请先阅读并同意服务协议和隐私政策');
      return;
    }
    const params = {
      checked: postData.checked,
      customerName: postData.customerName,
      organizingInstitutionCode: postData.organizingInstitutionCode,
      businessLicense: postData.businessLicense[0]?.url,
      businessCardStartDate: postData.businessCardStartDate,
      businessCardEndDate: postData.businessCardEndDate,
      legalPersonName: postData.legalPersonName,
      legalPersonIdNumber: postData.legalPersonIdNumber,
      legalPersonCardPictureObverse: postData.legalPersonCardPictureObverse[0]?.url || '',
      legalPersonCardPictureReverse: postData.legalPersonCardPictureReverse[0]?.url || '',
      legalPersonCardStartDate: postData.legalPersonCardStartDate,
      legalPersonCardEndDate: postData.legalPersonCardEndDate,
      contactMan: postData.contactMan,
      contactPhone: postData.contactPhone,
      registeredAddress: postData.registeredAddress,
      taxpayerId: postData.taxpayerId,
      depositBank: postData.depositBank,
      bankAccount: postData.bankAccount,
      account: postData.account,
      password: Md5.hashStr(postData.password),
      customerQualificationList: [
        {
          effectiveDate: postData.businessCardStartDate,
          expiredDate: postData.businessCardEndDate,
          qualificationImg: postData.businessLicense[0]?.url,
          qualificationType: 'BUSINESS_LICENSE',
        },
        {
          effectiveDate: postData.institutionCardStartDate,
          expiredDate: postData.institutionCardEndDate,
          qualificationImg: postData.medicalInstitution[0]?.url,
          qualificationType: 'MEDICAL_INSTITUTION_PRACTICING_LICENSE',
        },
      ],
    };
    loading.value = true;
    const { err } = await registerPost(params);
    if (err) {
      showToast(err);
    } else {
      showToast('注册成功，请等待后台审核');
    }
    loading.value = false;
  } catch (errors) {
    console.log('表单验证失败', errors);
  }
};

// 上传图片处理
const afterRead = async (file: any, type: string) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  formData.append('file', file.file);
  const { err, data } = await uploadPost(formData);
  if (err) {
    file.status = 'failed';
    file.message = '上传失败';
  } else {
    file.status = 'done';
    file.message = '上传成功';
  }
  postData[type] = [{ url: data }];
};
const beforeRead = (file: any) => {
  const isJPG =
    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    showToast('只能上传jpg/png/jpeg文件!');
  }
  if (!isLt1M) {
    showToast('上传图片大小不能超过 10MB!');
  }
  return isJPG && isLt1M;
};
const onClickServer = (type = 'policy') => {
  if (type === 'policy') {
    $router.push('/policy');
  } else if (type === 'password') {
    $router.push('/password');
  } else if (type === 'clause') {
    $router.push('/clause');
  } else if (type === 'register') {
    $router.push('/register');
  } else {
    $router.push('/policy');
  }
};

// 时间选择器
const showPicker = ref(false);
const selectPick = ref('');
const onShowPickClick = (type: string) => {
  showPicker.value = true;
  selectPick.value = type;
};
const onConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
  postData[selectPick.value] = selectedValues.join('/');
  showPicker.value = false;
};
</script>

<template>
  <div class="login-container">
    <van-form :model="postData" required="auto" :rules="rules" ref="formRef" label-width="7em">
      <div class="inputSpace">
        <van-field
          label="企业名称"
          placeholder="请输入企业名称"
          :rules="rules.customerName"
          v-model="postData.customerName"
          name="customerName"
        />
        <van-field
          label="组织机构代码"
          :rules="rules.organizingInstitutionCode"
          v-model="postData.organizingInstitutionCode"
          name="organizingInstitutionCode"
          placeholder="请输入组织机构代码"
        />
        <van-field
          label="营业执照"
          :rules="rules.businessLicense"
          name="businessLicense"
          placeholder="请上传营业执照"
        >
          <template #input>
            <van-uploader
              v-model="postData.businessLicense"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'businessLicense')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="证件生效日期"
          :rules="rules.businessCardStartDate"
          v-model="postData.businessCardStartDate"
          name="businessCardStartDate"
          placeholder="请选择证件生效日期"
          @click="onShowPickClick('businessCardStartDate')"
        />
        <van-field
          label="证件失效日期"
          :rules="rules.businessCardEndDate"
          v-model="postData.businessCardEndDate"
          name="businessCardEndDate"
          @click="onShowPickClick('businessCardEndDate')"
          placeholder="请选择证件失效日期"
        />
      </div>
      <div class="inputSpace">
        <van-field
          label="医疗机构执业许可证"
          :rules="rules.medicalInstitution"
          name="medicalInstitution"
          placeholder="请上传医疗机构执业许可证"
        >
          <template #input>
            <van-uploader
              v-model="postData.medicalInstitution"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'medicalInstitution')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="证件生效日期"
          :rules="rules.institutionCardStartDate"
          v-model="postData.institutionCardStartDate"
          @click="onShowPickClick('institutionCardStartDate')"
          name="institutionCardStartDate"
          placeholder="请选择证件生效日期"
        />
        <van-field
          label="证件失效日期"
          :rules="rules.institutionCardEndDate"
          v-model="postData.institutionCardEndDate"
          @click="onShowPickClick('institutionCardEndDate')"
          name="institutionCardEndDate"
          placeholder="请选择证件失效日期"
        />
      </div>
      <div class="inputSpace">
        <van-field
          label="法人姓名"
          :rules="rules.legalPersonName"
          name="legalPersonName"
          v-model="postData.legalPersonName"
          placeholder="请输入法人姓名"
        />
        <van-field
          label="身份证号"
          :rules="rules.legalPersonIdNumber"
          v-model="postData.legalPersonIdNumber"
          name="legalPersonIdNumber"
          placeholder="请输入法人身份证号"
        />
        <van-field
          label="身份证正面"
          :rules="rules.legalPersonCardPictureObverse"
          name="legalPersonCardPictureObverse"
          placeholder="请上传身份证正面"
        >
          <template #input>
            <van-uploader
              v-model="postData.legalPersonCardPictureObverse"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'legalPersonCardPictureObverse')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="身份证反面"
          :rules="rules.legalPersonCardPictureReverse"
          name="legalPersonCardPictureReverse"
          placeholder="请上传身份证正面"
        >
          <template #input>
            <van-uploader
              v-model="postData.legalPersonCardPictureReverse"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'legalPersonCardPictureReverse')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="证件生效日期"
          :rules="rules.legalPersonCardStartDate"
          name="legalPersonCardStartDate"
          v-model="postData.legalPersonCardStartDate"
          @click="onShowPickClick('legalPersonCardStartDate')"
          placeholder="点击选择证件生效日期"
        />
        <van-field
          label="证件失效日期"
          :rules="rules.legalPersonCardEndDate"
          v-model="postData.legalPersonCardEndDate"
          @click="onShowPickClick('legalPersonCardEndDate')"
          name="legalPersonCardEndDate"
          placeholder="请输入组织机构代码"
        />
      </div>
      <div class="inputSpace">
        <van-field
          label="联系人"
          :rules="rules.contactMan"
          v-model="postData.contactMan"
          name="contactMan"
          placeholder="请输入联系人"
        />
        <van-field
          label="联系电话"
          :rules="rules.contactPhone"
          v-model="postData.contactPhone"
          name="contactPhone"
          placeholder="请输入联系电话"
        />
        <van-field
          label="注册地址"
          :rules="rules.registeredAddress"
          v-model="postData.registeredAddress"
          name="registeredAddress"
          placeholder="请输入注册地址"
        />
        <van-field
          label="纳税识别号"
          :rules="rules.taxpayerId"
          v-model="postData.taxpayerId"
          name="taxpayerId"
          placeholder="请输入纳税识别号"
        />
        <van-field
          label="开户行"
          :rules="rules.depositBank"
          v-model="postData.depositBank"
          name="depositBank"
          placeholder="请输入开户行"
        />
        <van-field
          label="银行账号"
          :rules="rules.bankAccount"
          v-model="postData.bankAccount"
          name="bankAccount"
          placeholder="请输入银行账号"
        />
      </div>
      <div>
        <van-field
          label="登录手机号"
          :rules="rules.account"
          v-model="postData.account"
          name="account"
          placeholder="请输入登录手机号"
        />

        <van-field
          label="设置密码"
          placeholder="请输入密码"
          v-model="postData.password"
          :type="passwordShow"
          :rules="rules.password"
          name="password"
          @click-right-icon="passwordShow = passwordShow === 'password' ? 'text' : 'password'"
        >
          <template #right-icon>
            <div class="svgIcon">
              <svg-icon :icon-class="passwordShow === 'password' ? 'close' : 'open'" size="1.2em" />
            </div>
          </template>
        </van-field>

        <van-field
          label="确认密码"
          placeholder="请再次输入密码"
          v-model="postData.againPassword"
          :type="passwordShow"
          :rules="rules.againPassword"
          name="againPassword"
          @click-right-icon="passwordShow = passwordShow === 'password' ? 'text' : 'password'"
        >
          <template #right-icon>
            <div class="svgIcon">
              <svg-icon :icon-class="passwordShow === 'password' ? 'close' : 'open'" size="1.2em" />
            </div>
          </template>
        </van-field>
      </div>
      <div class="register_footer">
        <div class="checkbox">
          <van-checkbox
            checked-color="#00BA9F"
            v-model="postData.checked"
            label-disabled
            icon-size="12px"
          />
          <div class="checkText">
            我已阅读并同意
            <span @click="onClickServer('clause')" style="color: #00ba9f">
              《耶购网上医疗器械平台服务协议》
            </span>
            和
            <span @click="onClickServer('policy')" style="color: #00ba9f">
              《耶购网上医疗器械平台隐私政策》
            </span>
          </div>
        </div>
        <van-button :loading="loading" @click="onRegisterClick" color="#E89000" round block>
          登录
        </van-button>
        <div class="footer_message" @click="$router.push('/login')">已有账户，立即登录</div>
      </div>
    </van-form>
    <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
      <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  background: #f6f6f6;

  .inputSpace {
    margin-bottom: 4px;
  }

  .van-button {
    margin: 40px 0;
  }

  .register_footer {
    background: white;
    padding: 16px 16px 25px 16px;

    .checkbox {
      display: flex;
      align-items: flex-start;
      font-size: 12px;

      .van-checkbox {
        width: 30px;
        margin-top: 3px;
      }

      .checkText {
        color: #aaaaaa;
      }
    }

    .footer_message {
      width: 100%;
      display: flex;
      justify-content: center;
      font-size: 13px;
      color: #00ba9f;
    }

    .van-button {
      margin: 28px 0;
    }
  }
}
</style>
